package middleware

import (
	"finance/internal/utils"
	"github.com/gin-gonic/gin"
	"net/http"
	"strings"
)

func JWTAuthMiddleware() gin.HandlerFunc {
	return func(c *gin.Context) {
		authHeader := c.GetHeader("Authorization")
		if authHeader == "" {
			c.JSON(http.StatusUnauthorized, gin.H{
				"msg": "Missing Authorization header",
			})
			c.Abort() // abort the request(stop continue to execute after middleware or controller)
			return
		}
		tokenStr := strings.TrimPrefix(authHeader, "Bearer ") // trim the prefix
		claims, err := utils.ParseToken(tokenStr)
		if err != nil {
			c.JSON(http.StatusUnauthorized, gin.H{
				"msg": "Invalid or expired token",
			})
			c.Abort()
			return
		}
		c.Set("userID", claims.UserID)
		c.Set("username", claims.Username)
		c.Set("role", claims.RoleName)
		c.Set("roleID", claims.RoleID)

		c.Next() // continue to execute after middleware or controller handler
	}
}
